/* TODO

*/

if (typeof PIECESOFUK == "undefined") {
	var PIECESOFUK = {};
}

soundManager.url = 'javascript/soundmanager2.swf'

soundManager.onload = function() {
// soundManager.createSound({ id : ) etc. may now be called
 soundManager.createSound({ id : 'WWSYS', url : 'audio/WWSYS.mp3', autoLoad: true});
 soundManager.createSound({ id : 'YWMFM', url : 'audio/YWMFM.mp3', autoLoad: true});
 soundManager.createSound({ id : 'FG', url : 'audio/FG.mp3', autoLoad: true});
 soundManager.createSound({ id : 'MS', url : 'audio/MS.mp3', autoLoad: true});
 soundManager.createSound({ id : 'H', url : 'audio/Hands.mp3', autoLoad: true});
 soundManager.createSound({ id : 'DSL', url : 'audio/DSL.mp3', autoLoad: true});
 soundManager.createSound({ id : 'J', url : 'audio/Jupiter.mp3', autoLoad: true});
 soundManager.createSound({ id : 'LU', url : 'audio/LU.mp3', autoLoad: true});
 soundManager.createSound({ id : 'WSIT', url : 'audio/WSIT.mp3', autoLoad: true});
 soundManager.createSound({ id : 'SS', url : 'audio/SS.mp3', autoLoad: true});
 soundManager.createSound({ id : 'BM', url : 'audio/BM.mp3', autoLoad: true});
 soundManager.createSound({ id : 'TW', url : 'audio/TW.mp3', autoLoad: true});
 soundManager.createSound({ id : 'STE', url : 'audio/STE.mp3', autoLoad: true});
 soundManager.createSound({ id : 'I', url : 'audio/Intuition.mp3', autoLoad: true});
 soundManager.createSound({ id : 'S', url : 'audio/Stand.mp3', autoLoad: true});
 soundManager.createSound({ id : '2B1', url : 'audio/2Become1.mp3', autoLoad: true});
 soundManager.createSound({ id : 'AAA', url : 'audio/AaA.mp3', autoLoad: true});
 soundManager.createSound({ id : 'GD', url : 'audio/GoodDay.mp3', autoLoad: true});
 soundManager.createSound({ id : 'OOT', url : 'audio/OOT.mp3', autoLoad: true});
 soundManager.createSound({ id : 'SW', url : 'audio/SW.mp3', autoLoad: true});
 soundManager.createSound({ id : 'ID', url : 'audio/IDo.mp3', autoLoad: true});
 soundManager.createSound({ id : 'TIFLC', url : 'audio/TIFLC.mp3', autoLoad: true});

 soundManager.createSound( { id: "cheer", url : "audio/crowd-cheer.mp3", autoLoad: true});
 soundManager.createSound( { id: "groan", url : "audio/crowd-groan.mp3", autoLoad: true});

}

var hiPosition = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"];

var songIds = [ 'WWSYS', 'YWMFM', 'FG', 'MS', 'H', 'DSL', 'J', 'LU', 'WSIT', 'SS', 'BM',
                 'TW', 'STE', 'I', 'S', '2B1', 'AAA', 'GD', 'OOT', 'SW', 'ID', 'TIFLC'];

var songCovers = {
 "WWSYS" : "images/WWSYSSmall.jpg",
 "YWMFM" : "images/YWMFMSmall.jpg",
 "FG" : "images/FoolishGamesSmall.jpg",
 "MS" : "images/MorningSongSmall.jpg",
 "H" : "images/HandsSmall.jpg",
 "DSL" : "images/DownSoLongSmall.jpg",
 "J" : "images/JupiterSmall.jpg",
 "LU" : "images/LifeUncommonSmall.jpg",
 "WSIT" : "images/WSITSmall.jpg",
 "SS" : "images/StandingStillSmall.jpg",
 "BM" : "images/BreakMeSmall.jpg",
 "TW" : "images/ThisWaySmall.jpg",
 "STE" : "images/ServeTheEgoSmall.jpg",
 "I" : "images/IntuitionSmall.jpg",
 "S" : "images/StandSmall.jpg",
 "2B1" : "images/2Become1Small.jpg",
 "AAA" : "images/AgainAndAgainSmall.jpg",
 "GD" : "images/GoodDaySmall.jpg",
 "OOT" : "images/OnlyOneTooSmall.jpg",
 "SW" : "images/StrongerWomanSmall.jpg",
 "ID" : "images/IDoSmall.png",
 "TIFLC" : "images/TIFLCSmall.jpg"
};

	var xBanned = ["jdtg", "sotd", "rthq", "eqbst`c", "ntsng", "jo`x", "jsdk", "sjgt"];
	var banned = [];
  var numclicked = 0;
  var $firstClicked = null;
  var firstId = null;
  var $this = null;
  var theId = null;
  var startTime = null;

	var size;
	var matched = 0;
	var numSongs;
	var timer = null;

	var level = null;
	var type = null;

	var combo = null;

$(document).ready( function() {

	banned = decodeBanned(xBanned);
	$("#progress").hide();
	$("#about").hide();
	$("#message").html("Welcome to Jewel Pairs. For more information on Jewel please visit" +
										 " <a href='http://www.jewelfan.talktalk.net/Jewel/'>Jewel - Pieces of UK</a>.")
	setTimeout(startGameMessage, 10000);

	$(".disableable").attr("disabled", "");

  $("#hiscores").dialog( {title: "High Scores", position: ['right','bottom'],
												beforeclose: function() { return false; }});
  $("#controls").dialog( {title: "Jewel Pairs", position: ['right','top'],
												beforeclose: function() { return false; }});

  $("#infoBox").dialog( {title: "Info", position: ['right','middle'],
												beforeclose: function() { return false; }});


  $("#help").dialog( {title: "Jewel Pairs (help)"});

  $("#controls, #infoBox").show();
  getHiscores( $("#type").val(), $("#level").val() );

  $("#level").change( function() {
    getHiscores( $("#type").val(), $("#level").val() );
	});

  $("#type").change( function() {
    getHiscores( $("#type").val(), $("#level").val() );
	});

	$("#startButton").click( function() {
		begin();
	});

	$("#stopButton").click( function() {
	  $(".disableable").attr("disabled", "");
		clearTimeout(timer);
		$(".unselected").unbind("click");
	});

	$("#helpButton").click( function() {
    if ($("#help").dialog("isOpen")) $("#help").dialog("moveToTop");
			else $("#help").dialog("open");
	});


	$("#aboutButton").click( function() {
		if ( $("#about").hasClass("ui-dialog-content") ) {
      if ($("#about").dialog("isOpen")) $("#about").dialog("moveToTop");
			else $("#about").dialog("open");
		} else $("#about").dialog( {title: "Jewel Pairs (about)"});
	});

});

function startGameMessage() {
	if ( $("input[name=name]").val().replace(/ /g, "") == "" ) $("#message")
	    .text("Please enter your name then click Start Game to begin");
	else $("#message").text("Hello " + $("input[name=name]").val() + ", click Start Game to begin");

}

function getHiscores(type, level) {
	// nb the date attribute below added coz IE seems to have a caching problem
  $.get("/hiscores", {game : "Jewel Pairs", type: type, level: level, date: new Date() }, function(html) {
    $("#hiscores").html(html);
		$(".theTime").each( function() {
			var t = parseInt ( $(this).text(), 10);
			var secs = t % 60;
			var mins = Math.floor(t/60);
			$(this).text(mins + ":" + (secs < 10 ? "0" + secs : secs));
		});
		$("#hiscoreTable tr:odd").addClass("hiscoreStripe");
  });

}

function updateTimer() {
  var now = new Date();
  var secs = Math.floor ( (now - startTime) / 1000);
  var mins = Math.floor(secs/60);
  var secs = secs % 60;
  $("#timeSecs").text(secs < 10 ? "0" + secs : secs);
  $("#timeMins").text(mins);
  timer = setTimeout(updateTimer, 700);
}

function doFinish() {
	$("#progress").hide();
	$("#message").fadeIn("slow");
	clearTimeout(timer);
	var now = new Date();
  var totalSecs = Math.floor ( (now - startTime) / 1000);
  var mins = Math.floor(totalSecs/60);
  var secs = totalSecs % 60;
  $("#timeSecs").text(secs < 10 ? "0" + secs : secs);
  $("#timeMins").text(mins);
	var name = $("input[name=name]").val();
	$.post("/addhiscore", {
		game : "Jewel Pairs",
		type : type,
		level : level,
		score : totalSecs,
		name : $("input[name=name]").val()
	}, function(json) {
		  var minText = "minutes";
			if ( mins == 1 ) minText = "minute";
			var secText = "seconds";
			if ( secs == 1 ) secText = "second";
		  if (json.hiscore) {
				soundManager.play("cheer");
				alertUser("Well Done " + name + "! You finished in " + hiPosition[json.position] + " place in "
						+ mins + " " + minText + ", " + secs + " " + secText + ".");
			}	else {
				soundManager.play("groan");
				alertUser("Unlucky " + name + ", your time of "
					+ mins + " " + minText + ", " + secs + " " + secText + " wasn't quick enough.");
			}
		}, "json");
	setTimeout( 'getHiscores(type, level)', 5000); // added delay as the new hiscore wasn't getting picked up on live
	$(".disableable").attr("disabled", "");
}

function alertUser(message) {
	$("#infoBox").dialog("moveToTop")
	$("#message").text(message);
	$("#message").effect("pulsate", "fast");
}

function isNameValid(name) {
	if (name.length > 12 ) {
		alertUser("Sorry but the name is too long!");
		return false;
	}
	name = name.replace(/ /g, "");
	if ( name == "" ) {
		alertUser("Please enter a name");
		return false;
	}
	name = name.replace(/[\._ \-\*]/g, "").toLowerCase();
	for (var i = 0; i < banned.length; i++) {
		if ( name.match(banned[i]) ) {
		  alertUser("Sorry, but that name is not allowed.")
			return false;
		}
	}
  return true;
}

function begin() {
	if ( !isNameValid( $("input[name=name]").val() )) return;
	$("#pairs").html("");
	$(".disableable").attr("disabled", "disabled");
	$("#help").dialog("close");
	$("#infoBox").dialog("moveToTop")
	level = $("#level").val();
	type = $("#type").val();
	startTime = new Date();
  timer = setTimeout(updateTimer, 700);
	if (level == "Very Easy") {
    var numRows = 3;
    var numCols = 4;
	} else
	if (level == "Easy") {
    var numRows = 4;
    var numCols = 4;
	} else
	if (level == "Medium") {
    var numRows = 4;
    var numCols = 5;
	} else
	if (level == "Hard") {
    var numRows = 5;
    var numCols = 6;
	} else
	if (level == "Very Hard") {
    var numRows = 6;
    var numCols = 6;
	} else
	if (level == "Impossible") {
    var numRows = 6;
    var numCols = 7;
	}
  numSongs = numRows * numCols / 2;
	$("#matched").text(matched = 0);
	$("#progress").show();
	$("#message").text("").hide();

  for (var i = 0; i < songIds.length; i++) {
    var temp = songIds[i];
    var swap = Math.floor(Math.random()* songIds.length);
    songIds[i] = songIds[swap];
    songIds[swap] = temp;
  }

  var songsMap = new Array();
  var count = 0;
	var av = "av";
	if (Math.random() > .5) av = "va";
  for (var i = 0; i < numSongs; i++) {
//    songsMap[count++] = songIds[i];
//    songsMap[count++] = songIds[i];
    songsMap[count++] = av[0] + songIds[i];
    songsMap[count++] = av[1] + songIds[i];
  }

  for (var i = 0; i < songsMap.length; i++) {
    var temp = songsMap[i];
    var swap = Math.floor(Math.random()* songsMap.length);
    songsMap[i] = songsMap[swap];
    songsMap[swap] = temp;
  }

//  size = Math.floor( Math.min( ( $(document).height() - 40 ) / numRows , $(document).width() / numCols  ));
  size = Math.floor( Math.min( ( $(document).height() - 40 ) / numRows , ($("#pairs").width() - 20) / numCols  ));

  var idx = 0;
  for (var row = 0; row < numRows; ++row) {
    for (var col = 0; col < numCols; ++col) {
			var $img = $("<img>")
//				.attr("src", songCovers[songsMap[idx]])
				.attr("src", songCovers[songsMap[idx].slice(1)])
				.css("width", size + "px")
				.css("height", size + "px").hide();
			$("<div>")
//			.text(songsMap[idx]) // include for testing only
			  .append($img)
//				.data("songId", songsMap[idx])
				.data("combo", songsMap[idx].slice(0, 1))
				.data("songId", songsMap[idx].slice(1))
				.css("width", size + "px")
				.css("height", size + "px")
				.addClass("aSquare")
				.addClass("unselected")
				.appendTo( $("#pairs") )	;

			++idx;
    }
		$("#pairs").append("<br clear='left'>");
  }
  $(".unselected").click( handleClick );

}

function handleClick() {
  $(".unselected").unbind( "click");
  $this = $(this);
  $this.removeClass("unselected").addClass("selected");
  theId = $this.data("songId");
  if (numclicked == 0) firstClick();
	else if (type == "Combo") {
//		if ( combo == "Audio" ) $this.find("img").fadeIn("slow", checkMatch);
		if ( $this.data("combo") == "v" ) $this.find("img").fadeIn("slow", checkMatch);
		else soundManager.play(theId, {onfinish: checkMatch});
	}
	else if (type == "Audio") soundManager.play(theId, {onfinish: checkMatch});
	else $this.find("img").fadeIn("slow", checkMatch);
}

function firstClick() {
	if (type == "Combo") {
		if ( $this.data("combo") == "v" ) $this.find("img").fadeIn("slow");
		else soundManager.play(theId, {onfinish: null});

		/*
		if (Math.floor(Math.random()*2)) {
			combo = "Audio";
			soundManager.play(theId, {onfinish: null});
		} else {
			combo = "Visual";
			$this.find("img").fadeIn("slow");
		}
		*/
	}
	else if (type == "Audio") soundManager.play(theId, {onfinish: null});
	else $this.find("img").fadeIn("slow");
  $firstClicked = $this;
  firstId = theId;
  ++numclicked;
	$(".unselected").click( handleClick );
}

function checkMatch() {
  if ( theId && theId == firstId) {
    $this.addClass("matched");
    $firstClicked.addClass("matched");
		if (type == "Audio") {
		  $this.find("img").show();
		  $firstClicked.find("img").show();
		}
//		if (type == "Combo" && combo == "Visual") {
		if (type == "Combo" && $this.data("combo") == "a") {
      $this.find("img").show();
		}
//		if (type == "Combo" && combo == "Audio") {
		if (type == "Combo" && $firstClicked.data("combo") == "a") {
      $firstClicked.find("img").show();
		}

		$("#matched").text(++matched);
		if ( matched == numSongs ) doFinish();
  } else {
    $this.addClass("unselected");
    $firstClicked.addClass("unselected");
		if (type == "Visual") {
      $this.find("img").fadeOut("slow");
      $firstClicked.find("img").fadeOut("slow");
		}
//		if (type == "Combo" && combo == "Audio") {
		if (type == "Combo" && $this.data("combo") == "v") {
      $this.find("img").fadeOut("slow");
		}
//		if (type == "Combo" && combo == "Visual") {
		if (type == "Combo" && $firstClicked.data("combo") == "v") {
      $firstClicked.find("img").fadeOut("slow");
		}
  }
  $firstClicked.removeClass("selected");
  $this.removeClass("selected");
  $firstClicked = null;
	theId = null;
  firstId = null;
  numclicked = 0;
	$(".unselected").click( handleClick );
}

function decodeBanned(a) {
  var b = [];
  for (var i = 0; i < a.length; i++) {
    revWord = a[i].split("").reverse();
    encodedWord = $.map(revWord, function(item, i) { return String.fromCharCode(item.charCodeAt(0) - 1 + 2*(i%2))});
    b.push(encodedWord.join(""))
  }
  return b
}

function encodeBanned(a) {
  var b = [];
  for (var i = 0; i < a.length; i++) {
    var word = a[i].split("");
    encodedWord = $.map(word, function(item, i) { return String.fromCharCode (item.charCodeAt(0) + 1 + -2*(i%2))});
    var revWord = encodedWord.reverse();
    b.push(revWord.join(""));
  }
  return b;
}
